﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;


namespace EP2_LoginServer
{
    class Program
    {

        static void Main(string[] args)
        {

            try
            {

                Config.Read();
                mySQL.Test();

                TcpListener server = new TcpListener(Config.LoginServerIP, Config.LoginServerPort);

                server.Start();

                Byte[] bytes = new Byte[256];

                LogScreen.Info("EP2 LoginServer listening on "+ Config.LoginServerIP.ToString() +":"+ Config.LoginServerPort.ToString());
                
                while (true)
                {

                    TcpClient client = server.AcceptTcpClient();
                    NetworkStream stream = client.GetStream();

                    int i;

                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {

                        if (bytes[17] == 0x03)
                        {

                            string UserName = bytes.ReadString(23);
                            string Password = bytes.ReadString(23 + UserName.Length + 1);

                            if (mySQL.VerifyLogin(UserName, Password) == true)
                            {
                                stream.SendPack(Packages.ServerList());
                                LogScreen.Info("Success Login Attempt USER=" + UserName + " PASS=" + Password);
                            }
                            else
                            {
                                stream.SendPack(Packages.LoginFail());
                                LogScreen.Info("Failed Login Attempt USER=" + UserName + " PASS=" + Password);
                            }
                           
                        }

                    }

                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }


        }
 
    }
}
